package com.njwb.azqzb.job.Swing;


import com.njwb.azqzb.job.Util.HoseholdService;
import com.njwb.azqzb.job.pojo.HoseholdUsers;

import javax.swing.*;
import java.util.ArrayList;

public class HotelController {
    private HoseholdService service = new HoseholdService();
    private HotelView view;

    public HotelController(HotelView view) {
        this.view = view;
        init();
    }

    private void init() {
        // 初始化酒店下拉框
        view.comboBox.addItem("全部酒店");
        for (String name : service.getHotelNames()) {
            view.comboBox.addItem(name);
        }

        // 加载初始数据
        view.comboBox.setSelectedIndex(0);
        loadAllData();

        // 添加监听
        view.comboBox.addActionListener(e -> {
            String selected = (String) view.comboBox.getSelectedItem();
            if ("全部酒店".equals(selected)) {
                loadAllData();
            } else {
                loadHotelData(selected);
            }
        });

        view.addButton.addActionListener(e -> {
            new AddUserView(this).setVisible(true);
        });
    }

    public void loadAllData() {
        view.tableModel.setRowCount(0);
        ArrayList<HoseholdUsers> list = service.getAllHouseholdUsers();
        fillTable(list, "没有入住信息！");
    }

    public void loadHotelData(String hotelName) {
        view.tableModel.setRowCount(0);
        ArrayList<HoseholdUsers> list = service.getHouseholdUsersByHotelName(hotelName);
        fillTable(list, "该酒店没有入住信息！");
    }

    private void fillTable(ArrayList<HoseholdUsers> list, String emptyMsg) {
        for (HoseholdUsers u : list) {
            Object edate = (u.getEdata() == null || u.getEdata().toString().trim().isEmpty()) ? "未退房" : u.getEdata();
            view.tableModel.addRow(new Object[]{
                    u.getHotel(), u.getPlace(), u.getName(), u.getSdata(), edate
            });
        }

        if (list.isEmpty()) {
            JOptionPane.showMessageDialog(view, emptyMsg, "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public void refresh() {
        String selected = (String) view.comboBox.getSelectedItem();
        if ("全部酒店".equals(selected)) {
            loadAllData();
        } else {
            loadHotelData(selected);
        }
    }

    public HoseholdService getService() {
        return service;
    }
}
